using System;
using System.Xml;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxEditors;
using System.Drawing.Imaging;
using DevExpress.Web.ASPxTabControl;
using DevExpress.Web.ASPxUploadControl;
using DevExpress.Web.ASPxHtmlEditor;
using DevExpress.Web.ASPxCallback;
using Indeco.G24.Web;
using Indeco.G24.Web.Data;
using Indeco.G24.Data;
using Indeco.G24.Services;
using Indeco.G24.Entities; 

namespace Indeco.G24.Website.News.Admin
{
    public partial class TinTuc : G24Page
    {
        private string _siteMapFileName = "SiteMap/NewsOfCategory.sitemap";
        private const String SiteMapNodeName = "siteMapNode";
        public string domain = ""; 
        Guid g = Guid.Empty;
        public NhaCungCap nhacc = new NhaCungCap();
        protected void Page_Load(object sender, EventArgs e)
        {
            string path = "http://" + Request.Url.Host;
            if (Request.Url.Port != null || Request.Url.Port > 0) path += ":" + Request.Url.Port.ToString();
            if (!string.IsNullOrEmpty(Request.ApplicationPath)) path += Request.ApplicationPath;
            domain = path;
            lblCatIDSelected.Text = g.ToString();
            try
            {
                if (Session["IDNguoiDung"] != null)
                {
                    if (Session["IDNguoiDung"].ToString() == Guid.Empty.ToString())
                    {
                        Session["TenNhaCungCap"] = null;
                    }
                    else
                    {
                        NguoiDungNhaCungCapService nguoiDungNhaCungCapService = new NguoiDungNhaCungCapService();
                        NhaCungCapService nhaccService = new NhaCungCapService();
                        TList<NguoiDungNhaCungCap> listNN = nguoiDungNhaCungCapService.GetByIDNguoiDung(new Guid(Session["IDNguoiDung"].ToString()));
                        nhacc = nhaccService.GetByIDNhaCungCap(new Guid(listNN[0].IDNhaCungCap.ToString()));
                        Session["TenNhaCungCap"] = (nhacc.Ten != null) ? nhacc.Ten : null;
                    }
                }
                else
                    Session["TenNhaCungCap"] = null;
            }
            catch
            {

            }
        } 
        protected void ASPxUploadControl1_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            if ((sender as ASPxUploadControl).IsValid)
            {
                DateTime time = DateTime.Now;
                string filename = uploadNewsImages((sender as ASPxUploadControl).FileName.ToString(), (sender as ASPxUploadControl), 90, 90, Request.PhysicalApplicationPath + "Data/Images/News");
                string path = "http://" + Request.Url.Host;
                if (Request.Url.Port != null) path += ":" + Request.Url.Port.ToString();
                if (!string.IsNullOrEmpty(Request.ApplicationPath)) path += Request.ApplicationPath;
                Session["data"] = path+ "Data/Images/News/" + filename;//.FileBytes;                 
               
            }
        }
        #region Save Image
        public static string uploadNewsImages(String UploadedFile, ASPxUploadControl inputFile, int imageHeight, int imageWidth, string folder)
        {
            DateTime MyDate = DateTime.Now;
            String UploadedFileName = MyDate.ToString("ddMMyyhhmmss") + ".jpg";
            try
            {
                int ExtractPos = UploadedFile.LastIndexOf("\\") + 1;
                //String UploadedFileName = UploadedFile.Substring(ExtractPos, UploadedFile.Length - ExtractPos);
                inputFile.SaveAs(folder + "\\" + UploadedFileName);
                //thumbnail creation starts
                String imageUrl = folder + "\\" + UploadedFileName;
                System.Drawing.Image fullSizeImg = System.Drawing.Image.FromFile(imageUrl);
                System.Drawing.Image.GetThumbnailImageAbort dummyCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
                System.Drawing.Image thumbNailImg = fullSizeImg.GetThumbnailImage(imageWidth, imageHeight, dummyCallBack, IntPtr.Zero);
                String MyString = UploadedFileName + "_thumb.jpg";
                thumbNailImg.Save(folder + "\\" + MyString, ImageFormat.Jpeg);
                thumbNailImg.Dispose();
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            return UploadedFileName;
        }

        private static bool ThumbnailCallback()
        {
            return false;
        }
        #endregion               

        protected void ASPxGridView3_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {
            ASPxGridView grid = sender as ASPxGridView;           
            ASPxImage img = grid.FindEditRowCellTemplateControl((GridViewDataColumn)grid.Columns["HinhMinhHoa"], "HinhMinhHoa") as ASPxImage;
            DropDownList dt = grid.FindEditRowCellTemplateControl((GridViewDataColumn)grid.Columns["IDTinTucDanhMuc"], "Custommize") as DropDownList;
            if (dt != null)
            { 
               
            }
            e.NewValues["NhaCungCap"] = Session["TenNhaCungCap"];          
            e.NewValues["ThoiDiemCapNhat"] = DateTime.Now;
            e.NewValues["ThoiDiemChinhSua"] = DateTime.Now;
            if (Session["data"] != null && Session["data"].ToString() != "")
            {
                e.NewValues["HinhMinhHoa"] = Session["data"];
                Session["data"] = null;
            }
            else
                e.NewValues["HinhMinhHoa"] = "";
            //generalSiteMap();
        }

        protected void ASPxGridView3_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            ASPxGridView grid = sender as ASPxGridView;
            ASPxImage img = grid.FindEditRowCellTemplateControl((GridViewDataColumn)grid.Columns["HinhMinhHoa"], "HinhMinhHoa") as ASPxImage;
            e.NewValues["NhaCungCap"] = Session["TenNhaCungCap"];
            e.NewValues["ThoiDiemCapNhat"] = DateTime.Now;
            e.NewValues["ThoiDiemChinhSua"] = DateTime.Now;
            if (Session["data"] != null && Session["data"].ToString() != "")
            {
                e.NewValues["HinhMinhHoa"] = Session["data"];
                Session["data"] = null;
            }
           // generalSiteMap();
        }

        protected void ASPxGridView3_StartRowEditing(object sender, DevExpress.Web.Data.ASPxStartRowEditingEventArgs e)
        {
            ASPxGridView grid = sender as ASPxGridView;
            
        }
        private void loadFolder(XmlElement rootElement)
        {
            TList<TinTucDanhMuc> danhmuccha = DataRepository.TinTucDanhMucProvider.Find("id_tintucdanhmuccha='" + Guid.Empty.ToString() + "'");
            if (danhmuccha.Count > 0)
            {
                foreach (TinTucDanhMuc dm in danhmuccha)
                {
                    XmlElement teams = AddDynamicChildElement(rootElement, "~/News/Category.aspx?IDTinTucDanhMuc=" + dm.IDTinTucDanhMuc.ToString(), dm.Ten, "");
                    TList<TinTucDanhMuc> danhmucon = DataRepository.TinTucDanhMucProvider.Find("id_tintucdanhmuccha='" + dm.IDTinTucDanhMuc + "'");
                    if (danhmucon.Count > 0)
                    {
                        foreach (TinTucDanhMuc dmc in danhmucon)
                        {
                            TList<Indeco.G24.Entities.TinTuc> tin = DataRepository.TinTucProvider.Find("id_tintucdanhmuc='" + dmc.IDTinTucDanhMuc.ToString() + "'");
                            if (tin.Count > 0)
                            {
                                foreach (Indeco.G24.Entities.TinTuc t in tin)
                                {
                                    AddDynamicChildElement(teams, "~/News/Category.aspx?IDTinTucDanhMuc=" + dmc.IDTinTucDanhMuc.ToString() + "&IDTinTuc=" + t.IDTinTuc.ToString() + "", dmc.Ten, "");
                                }
                            }

                        }
                    }
                }
            }
        }
        public void generalSiteMap()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + _siteMapFileName;
            System.IO.File.SetAttributes(path, FileAttributes.Archive);
            XmlDocument siteMapXml = new XmlDocument();
            siteMapXml.Load(AppDomain.CurrentDomain.BaseDirectory + _siteMapFileName);
            XmlElement rootElement = (XmlElement)siteMapXml.GetElementsByTagName(SiteMapNodeName)[0];
            rootElement.RemoveAll();
            rootElement.SetAttribute("url", "~/News/Default.aspx");
            rootElement.SetAttribute("title", "Tin Tuc");
            rootElement.SetAttribute("description", "");
            saveXML(siteMapXml, path);
            loadFolder(rootElement);
            saveXML(siteMapXml, path);
        }
        private void saveXML(XmlDocument docXml, string path)
        {
            try
            {
                docXml.Save(path);
            }
            catch { }
        }
        private static XmlElement AddDynamicChildElement(XmlElement parentElement, String url, String title, String description)
        {           
            // Create new element from the parameters
            XmlElement childElement = parentElement.OwnerDocument.CreateElement(SiteMapNodeName, "http://schemas.microsoft.com/AspNet/SiteMap-File-1.0");
            childElement.SetAttribute("url", url);
            childElement.SetAttribute("title", title);
            childElement.SetAttribute("description", description);
            // Add it to the parent
            parentElement.AppendChild(childElement);
            return childElement;
        }

        protected void ASPxGridView3_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
        {
            string fileName = e.Values["HinhMinhHoa"].ToString();          
            if (!string.IsNullOrEmpty(fileName))
            {
                DirectoryInfo dir = new DirectoryInfo(Server.MapPath(@"~\" + @"Data/Images/News/"));
                try
                {
                    int i = fileName.LastIndexOf('/');
                    if (i > -1)
                    {
                        string name = fileName.Substring(i + 1);
                        System.IO.File.SetAttributes(dir + "\\" + name, FileAttributes.Archive);
                        System.IO.File.SetAttributes(dir + "\\" + name + "_thumb.jpg", FileAttributes.Archive);
                        File.Delete(dir + "\\" + name);
                        File.Delete(dir + "\\" + name + "_thumb.jpg");
                    }
                }
                catch
                {
                }
            }
        }

        protected void ASPxGridView3_RowInserted(object sender, DevExpress.Web.Data.ASPxDataInsertedEventArgs e)
        {
          //  generalSiteMap();
        }

        protected void ASPxGridView3_RowDeleted(object sender, DevExpress.Web.Data.ASPxDataDeletedEventArgs e)
        {
           // generalSiteMap();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            generalSiteMap();
        }
           
    }
}
